<template>
  <div>
    <!-- 面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- card区-->
    <el-card>
      <!-- 输入框区-->
      <el-row>
        <el-col :span="10">
          <el-input
            placeholder="请输入搜索内容"
            width="200px"
            clearable
            v-model="paramsData.query"
            @clear="getUserData"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserData"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" class="addBtn" @click="userDialog = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格区-->
      <el-table :data="usersTableData" border style="width: 100%">
        <el-table-column type="index" label="#" width="80"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        ></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              @change="stateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="权限">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserInfo(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="分配权限"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-star-off"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsData.pagenum"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="paramsData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框区域-->
    <el-dialog title="添加用户" :visible.sync="userDialog" @close="dialogClose">
      <el-form
        ref="userDialogRef"
        :model="userDialongform"
        :rules="userDialogRules"
        label-width="120px"
      >
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="userDialongform.username"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="userDialongform.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="userDialongform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="mobile">
          <el-input v-model="userDialongform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户对话框区域-->
    <el-dialog
      title="编辑用户"
      :visible.sync="editUserDialog"
      @close="editDialogClose"
    >
      <el-form
        ref="editUserDialogRef"
        :model="editUserDialongform"
        :rules="editUserDialogRules"
        label-width="120px"
      >
        <el-form-item label="用户名：">
          <el-input disabled v-model="editUserDialongform.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="editUserDialongform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="mobile">
          <el-input v-model="editUserDialongform.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUsers">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
import {requestUsersData, requestChangeState,requestAddUsers,requestEditUsers, requestEditUsersID, requestDeleteUsers} from "@/network/users.js"
export default {
    data() {
      // 验证邮箱的规则
      var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
      }
      // 验证手机号的规则
      var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
      }
    return {
        //传递的参数
        paramsData:{
            query: '',
            pagenum: 1,
            pagesize: 2
        },
        //表格数据
        usersTableData: [],
        total: 0,
        userDialog: false,
        //Dialog里面的输入框数据
        userDialongform:{
          username:'',
          password:'',
          email:'',
          mobile:''
        },
        //添加用户的验证规则
        userDialogRules:{
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
            {validator: checkEmail, trigger: 'blur'}
          ],
          mobile:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
            {validator: checkMobile, trigger: 'blur'}
          ]
        },
        //编辑用户对话框的显示和隐藏
        editUserDialog: false,
        //编辑用户的输入框信息
        editUserDialongform:{},
        //编辑用户的验证规则
        editUserDialogRules:{
          email:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
            {validator: checkEmail, trigger: 'blur'}
          ],
          mobile:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
            {validator: checkMobile, trigger: 'blur'}
          ]
        },
        editUserId: ''

        }
    },
    created() {
        this.getUserData()
    },
    methods: {
        //改变每页展示多少条数据时触发的函数
        handleSizeChange(value){
          this.paramsData.pagesize = value
          this.getUserData()
        },
        //改变页码值时触发的函数
        handleCurrentChange(value){
          this.paramsData.pagenum = value
          this.getUserData()
        },
        //关闭添加用户信息对话框时触发的事件函数
        dialogClose(){
          this.$refs.userDialogRef.resetFields()
        },
        //关闭编辑用户信息对话框时触发的事件函数
        editDialogClose(){
          this.$refs.editUserDialogRef.resetFields()
        },


        /**
        网络请求相关的函数
         */
        //发送网络请求，获取数据
        async getUserData(){
            const {data} = await requestUsersData({params: this.paramsData})
            if(data.meta.status !== 200) return this.$message.error('获取用户列表数据失败')
            this.usersTableData = data.data.users
            this.total = data.data.total
        },
        //发送网络请求,更新状态
        async stateChange(row){
          // row.mg_state = !row.mg_state
          console.log(row.mg_state);
          const {data} = await requestChangeState({url:`users/${row.id}/state/${row.mg_state}`})
          if(data.meta.status !== 200){
            row.mg_state = !row.mg_state
            return this.$message.error('更新状态信息失败')

          }
          return this.$message.success('更新状态成功')
        },
        //添加用户操作
        addUsers(){
          this.$refs.userDialogRef.validate(async valid =>{
            if(!valid){
              return this.$message.error('您输入的格式不正确')
            }else{
              const {data} = await requestAddUsers({data:this.userDialongform})
              if(data.meta.status !== 201) return this.$message.error('用户信息添加失败')
              this.$message.success('用户信息添加成功')
              this.getUserData()
              this.userDialog = false
            }
          })
        },
        //编辑用户的提交操作
        editUsers(){
          this.$refs.editUserDialogRef.validate(async valid =>{
             if(!valid){
              return this.$message.error('您输入的格式不正确')
            }else{
              const {data} = await requestEditUsers({url:`users/${this.editUserId}`,data:this.editUserDialongform})
              if(data.meta.status !== 200) return this.$message.error('用户信息编辑失败')
              this.$message.success('用户信息编辑成功')
              this.getUserData()
              this.editUserDialog = false
            }
          })
        },
        //点击编辑按钮，并根据ID查询编辑用户的信息
        async editUserInfo(userInfo){
          //把形参中的数据填充进编辑的对话框中
          this.editUserDialog = true
          this.editUserId = userInfo.id
          const {data} = await requestEditUsersID({url:`users/${userInfo.id}`})
          if(data.meta.status !== 200) return this.$message.error('查询用户信息失败')
          this.editUserDialongform = data.data
        },
        //删除用户信息时触发的事件函数
        async deleteUser(userId){
          const res = await this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
        if(res === 'confirm'){
          const {data} = await requestDeleteUsers({url:`users/${userId}`})
          if(data.meta.status !== 200) return this.$message.error('删除用户失败')
          this.$message.success('删除用户信息成功')
          this.getUserData()
          
          
        }
        
        }

      },
    }
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
  .addBtn {
    margin-left: 30px;
  }
  .el-table {
    margin-top: 20px;
    margin-bottom: 20px;
  }
}
</style>
